//wholehouse.js
import {
  ismsHouseBuyinfo, verifySpaceValidation
} from '../../../../../config/config'
var configUrl = require('../../../../../config/config') //引入配置接口文件
var getuRL = require('../../../../../utils/util') //引入js过滤方法
//获取应用实例
const app = getApp()

Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isIPXBottom:app.globalData.isIPXBottom,
    imgUrl: getApp().globalData.imgUrl,
    activeIcon: '../../../../../image/imgs/icon_check.png',
    inactiveIcon: '../../../../../image/imgs/icon_unchecked.png',
    /**-------------------- */
    show: false,
    modelPopup: false,
    changeImg: 0, //默认展示第一张空间主图
    roomGoods: 0, //默认展示第一张空间商品列表
    showOtherAddr:false, 
    subBtnDis:false,
  },
  onLoad: function (res) {
    
    let that = this
    let addrCode = wx.getStorageSync('addrCode')
    that.setData({
      addrCode: addrCode
    })
    if(app.globalData.isIPXBottom){
      this.setData({isIPXBottom:app.globalData.isIPXBottom})     
    }else{
      this.setData({isIPXBottom:'0px'})
    }
    if (res) {
      console.log(res)
      let activityId = JSON.parse(res.option).activityId
      let mealId = JSON.parse(res.option).id
      // let activityId = res.activityId
      // let mealId = res.id
      that.setData({
        activityId: activityId,
        mealId: mealId
      })   
    }
      that.getAddressList()
  },
  listSelect(e) { //切换空间展示商品
    var index = e.currentTarget.dataset.index
    let that = this
    that.setData({
      roomGoods: index
    })
    this.imglistSelect(e)
  },
  imglistSelect(e) { //切换展示空间图片
    var index = e.currentTarget.dataset.index
    let that = this
    that.setData({
      changeImg: index
    })
  },
  getScroll(e) {
    console.log('e', e)
  },

  // 获取详情数据
  getDetails(addrCode) {
    let that = this
    let params = {
      'activityId': that.data.activityId,
      'tailAddrCode': addrCode,
      'chooses': [],
      'mealId': that.data.mealId
    }
    app.reqFun.requestJson('POST', ismsHouseBuyinfo, params, (res) => {
      if (res.data.success == 1) {
        var oldInfo=that.data.infoData
        if(oldInfo){  //匹配已选择数据
          var sletSku=[]
          let infoData = res.data.data
          for (let room of oldInfo.smsHouseBuyMealSpaceInfoDto) {
            for (let sku of room.pmsHouseBuyProductDto) {
              sku.skuStock.forEach(function (item, index) {
                if (item.isCheck) {
                  sletSku.push(item.skuId)
                }
              })
            }
          }
          for (let room of infoData.smsHouseBuyMealSpaceInfoDto) {
            for (let sku of room.pmsHouseBuyProductDto) {
              sku.skuStock.forEach(function (item, index) {
                for(let sid of sletSku){
                  if (item.skuId==sid) {
                    item.isCheck = true
                  }
                }      
              })
            }
          }
          infoData.totalAmount=0
          that.getReturnTime(infoData.activeEndDate)  //调用倒计时
          that.setData({
            infoData: infoData,
          })
          that.calculationPriceOrNumber(infoData)

        }else{  //初始化数据
          let infoData = res.data.data
          
          for (let room of infoData.smsHouseBuyMealSpaceInfoDto) {
            for (let sku of room.pmsHouseBuyProductDto) {
              sku.skuStock.forEach(function (item, index) {
                if (index == 0) {
                  item.isCheck = true
                }
              })
            }
          }
          infoData.totalAmount=0
          that.getReturnTime(infoData.activeEndDate)  //调用倒计时
          that.setData({
            infoData: infoData,
          })
          that.calculationPriceOrNumber(infoData)
        }
        
      }
    })
  },

  checkboxChange(e) { //选择空间
    let value = e.currentTarget.dataset.value
    let ck = e.currentTarget.dataset.ck
    var info=this.data.infoData
    let mealData = this.data.infoData.smsHouseBuyMealSpaceInfoDto
    for (var i = 0, len = mealData.length; i < len; i++) {
      if (value == mealData[i].id) {
        if(mealData[i].checked){
          mealData[i].checked=false
        }else{
          mealData[i].checked=true
        }
      }
    }
    info.smsHouseBuyMealSpaceInfoDto=mealData
    this.setData({
      infoData:info
    });
    this.calculationBuyPrice(info)
  },
  // 关闭空间弹框
  onCloseModel() {
    this.setData({
      show: false
    })
  },
  buyNow() {  //购买弹窗
    let that = this
    app.getLogin((re)=>{
      if(re){
        that.setData({
          show: true
        })
      } else {
        if (wx.getUserProfile) {
          app.getUserProfile(function(){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          })
        } else {
          if(!wx.getStorageSync('loginMsg').bindingPhone){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          }
        }
        // that.setData({
        //   isShowGetUserInfo: true
        // })
      }
    })
  },
  selectSpecific(e) { //打开属性规格弹窗
    var thisSku = e.currentTarget.dataset.val
    console.log(thisSku)
    this.setData({
      modelPopup: true,
      thisSku: thisSku,
      thisSpuPic:thisSku.pic
    })
    this.initAttrBox(thisSku)
  },
  initAttrBox(nowSku) { //初始化选择属性框
    var that = this;
    var infoData = this.data.infoData
    var skusAttr = [];
    var selectSku = ''
    var allAttr = []
    for (let val of nowSku.skuStock) {
      if (val.isCheck) {
        selectSku = val
        that.setData({
          selectSkuId: val.skuId,
          ShowselectSku: val,
          seletSkuList: nowSku
        })
      }
      var attr = JSON.parse(val.productAttr)
      allAttr.push(attr)
      for (let arr of attr) {
        skusAttr.push(arr)
      }
    }

    that.setData({
      skusAttr: skusAttr,
      allAttr: allAttr
    })

    that.setData({
      allStatusMap: nowSku.attrChooseable //规格属性选择框数据
    })
    //对象封装去重
    var keys = []
    for (let at of skusAttr) {
      keys.push({
        key: at.key,
        keyName: at.key_name
      })
    }
    keys = this.norepeat(keys, 1)
    for (var i = 0; i < keys.length; i++) {
      var values = []
      for (let val of skusAttr) {
        if (keys[i].keyName == val.key_name) {
          values.push({
            id: val.value,
            value: val.value_name,
            disabled: true,
            isCheck: false
          })
        }
      }
      values = this.norepeat(values)
      keys[i].value = values
    }

    /**匹配默认选中 */
    var enSelectItem = []
    var allChecked = []
    var newSelectItem = []
    console.log(selectSku)
    var selectSkuAttr = JSON.parse(selectSku.productAttr)
    for (let k of selectSkuAttr) {
      for (let obj of this.data.allStatusMap) {
        if (obj.attrItemId == k.value) {
          enSelectItem.push(k.value)
          for (let i of obj.chooseAbleItem) {
            enSelectItem.push(i)
          }
        }
      }
    }
    for (let val of keys) {
      for (var i = 0; i < val.value.length; i++) {
        if (JSON.stringify(enSelectItem).indexOf(JSON.stringify(val.value[i].id)) != -1) {
          console.log(val)
          val.value[i].disabled = false
          for (let k of selectSkuAttr) {
            if (val.value[i].id == k.value) {
              val.value[i].isCheck = true
              allChecked.push(val.value[i].id)
            }
          }
        } else {
          if (obj.isCheck == false) {
            obj.disabled = true
          }
        }

      }
    }
    var letbiobj = this.getRepeatNum(enSelectItem)
    if (allChecked.length > 1) {
      for (let k of enSelectItem) {
        if (letbiobj[k] == allChecked.length) {
          if (JSON.stringify(newSelectItem).indexOf(JSON.stringify(k)) < 0) {
            newSelectItem.push(k)
          }
        }
      }
      for (let val of keys) {
        for (let obj of val.value) {
          if (JSON.stringify(newSelectItem).indexOf(JSON.stringify(obj.id)) != -1) {
            obj.disabled = false
          } else {
            if (obj.isCheck == false) {
              obj.disabled = true
            }
          }

        }
      }

    }
    that.setData({
      AttrBoxData: keys //规格属性选择框数据
    })
    this.getSelectAttrToSku(keys)
  },
  norepeat(arr, type) { //初始化属性数据去重
    for (var i = 0; i < arr.length - 1; i++) {
      for (var j = i + 1; j < arr.length; j++) {
        if (type == 1) { //key  去重
          if (arr[i].key == arr[j].key) {
            arr.splice(j, 1);
            j--;
          }
        } else { //value  去重
          if (arr[i].value == arr[j].value) {
            arr.splice(j, 1);
            j--;
          }
        }

      }
    }
    return arr;
  },
  selectAttr(e) { //选择sku交互
    if (e.currentTarget.dataset.dis == false) {
      var AttrBoxData = this.data.AttrBoxData
      var selectId = e.currentTarget.dataset.id
      var keyname = e.currentTarget.dataset.item.keyName
      var enSelectItem = []
      var allChecked = []
      var newSelectItem = []
      for (let val of AttrBoxData) {
        if (val.keyName == keyname) {
          for (let va of val.value) {
            if (selectId == va.id) {
              if (va.isCheck) {
                va.isCheck = false
              } else {
                va.isCheck = true
              }
            } else {
              va.isCheck = false
            }
          }
        }
        for (let va of val.value) {
          if (va.isCheck == true) {
            allChecked.push(va)
            for (let obj of this.data.allStatusMap) {
              if (obj.attrItemId == va.id) {
                for (let i of obj.chooseAbleItem) {
                  enSelectItem.push(i)
                }
              }
            }
          }
        }
      }

      var letbiobj = this.getRepeatNum(enSelectItem)
      if (allChecked.length) {
        for (let k of enSelectItem) {
          if (letbiobj[k] == allChecked.length) {
            if (JSON.stringify(newSelectItem).indexOf(JSON.stringify(k)) < 0) {
              newSelectItem.push(k)
            }
          }
        }
        for (let val of AttrBoxData) {
          for (let obj of val.value) {
            if (JSON.stringify(newSelectItem).indexOf(JSON.stringify(obj.id)) != -1) {
              obj.disabled = false
            } else {
              if (obj.isCheck == false) {
                obj.disabled = true
              }
            }

          }
        }

      } else {
        for (let val of AttrBoxData) {
          for (let obj of val.value) {
            obj.disabled = false
          }
        }

      }
      this.setData({
        AttrBoxData: AttrBoxData
      })
      this.getSelectAttrToSku(AttrBoxData, e.currentTarget.dataset.item)
    }
  },
  //集合检索
  getRepeatNum(arr) {
    var obj = {};
    for (var i = 0, l = arr.length; i < l; i++) {
      var item = arr[i];
      obj[item] = (obj[item] + 1) || 1;
    }
    return obj;
  },

  getSelectAttrToSku(list) { //已选项匹配赛选SKU
    var skuList = this.data.seletSkuList
    var sletAtr = [] //选中的属性
    var selectNum = 0 ///选中的属性数量
    var allNum = 0 //可选分类属性数
    for (let atr of list) {
      allNum = allNum + 1
      for (let at of atr.value) {
        if (at.isCheck) {
          selectNum = selectNum + 1;
          sletAtr.push({
            key: atr.key,
            keyName: atr.keyName,
            vId: at.id,
            value: at.value
          })
        }
      }
    }
    if (selectNum == allNum) { //属性是否已选完
      this.setData({
        btnTrueClick: true
      })
      var arrList = skuList.skuStock
      var sskuList = []
      for (let val of arrList) {
        for (let at of JSON.parse(val.productAttr)) {
          for (let sat of sletAtr) {
            if (at.key == sat.key && at.value == sat.vId) {
              sskuList.push(val.skuId)
            }
          }

        }
      }
      if (allNum == 1) {
        this.setData({
          selectSkuId: sskuList[0]
        })
      } else {
        this.setData({
          selectSkuId: this.getOneSku(sskuList).skuId
        })
      }
    } else {
      this.setData({
        btnTrueClick: false
      })
    }
    for (let sku of arrList) {
      if (this.data.selectSkuId == sku.skuId) {
        this.setData({
          thisSku: sku
        })
      }
    }
  },
  getOneSku(slectNum) { //筛选出已选项匹配的Sku
    if (!slectNum) return false;
    if (slectNum.length === 1) return 1;
    let res = {}
    let maxNum = 0;
    let maxValue = null;
    for (let i = 0; i < slectNum.length; i++) {
      let val = slectNum[i]
      res[val] === undefined ? res[val] = 1 : res[val]++;
      if (res[val] > maxNum) {
        maxNum = res[val];
        maxValue = val
      }
    }
    return {
      skuId: maxValue,
      num: maxNum
    }
  },
  // 关闭规格属性弹窗
  onCloseModel(e) {
    this.setData({
      modelPopup: false,
      show:false,
    })
  },
  // 确定规格属性选项
  determine() {
    var skuid = this.data.thisSku
    var info = this.data.infoData
    var spu = ''
    for (let li of info.smsHouseBuyMealSpaceInfoDto) {
      for (let skl of li.pmsHouseBuyProductDto) {
        for (let sk of skl.skuStock) {
          if (skuid.skuId == sk.skuId) {
            spu = skl
          }
        }
      }
    }
    for (let sku of spu.skuStock) {
      sku.isCheck = false
      if (sku.skuId == skuid.skuId) {
        sku.isCheck = true
      }
    }
    for (let li of info.smsHouseBuyMealSpaceInfoDto) {
      for (let skl of li.pmsHouseBuyProductDto) {
        if (skl.id == spu.id) {
          skl = spu
        }
      }
    }
    this.setData({
      modelPopup: false,
      infoData: info
    })
    this.calculationPriceOrNumber(info)
  },
  selectModel(e){  //打开地区弹窗
    this.setData({
      showOtherAddr:false,
      modelPopupName:e.currentTarget.dataset.popup
    }) 
  },
  selectOhterAddr(){  //选择其他收货地址
    this.setData({
      showOtherAddr:true,
      sprovince:'',
      scity:'',
      sregion:'',
      sstreetName:''
    })    
    this.getAddressSelectData()
  },
  restSelect(e){  //重新选择
    if(e.currentTarget.dataset.val==2){
      this.setData({sprovince:'',scity:'',sregion:'',sstreetName:''})
      this.getAddressSelectData()
    }else if(e.currentTarget.dataset.val==3){
      this.setData({scity:'',sregion:'',sstreetName:''})
      this.getAddressSelectData(e.currentTarget.dataset.item,true)
    }else if(e.currentTarget.dataset.val==4){
      this.setData({sregion:'',sstreetName:''})
      this.getAddressSelectData(e.currentTarget.dataset.item,true)
    }
  },  
  getAddressSelectData(e,aa){  //查询4级地址数据
    var that=this;
    var parms={parentCode:100000000000}
    var data=""
    if(e){
      if(aa){
        data=e
      }else{
        data=e.currentTarget.dataset.val
      }  
      console.log(data)
      parms.parentCode=data.code
      if(data.areaLevel==2){
        that.setData({sprovince:data})
      }else if(data.areaLevel==3){
        that.setData({scity:data})
      }else if(data.areaLevel==4){
        that.setData({sregion:data})
      }else if(data.areaLevel==5){
        that.setData({sstreetName:data})
      }
    } 
    app.reqFun.requestJson('get',configUrl.listByParentCode,parms,(res)=>{
      if(res.data.success==1){ 
        if(res.data.data.length>0){
          that.setData({
            itemsAddr: res.data.data,      
          })
        }else{
          that.setData({  //关闭弹窗
            modelPopupName:'',
            showOtherAddr:false
          })
          var temporaryAddressData={}
          temporaryAddressData.province=that.data.sprovince
          temporaryAddressData.city=that.data.scity
          temporaryAddressData.region=that.data.sregion
          temporaryAddressData.streetName=that.data.sstreetName
          wx.setStorageSync('temporaryAddressData', temporaryAddressData)
          wx.removeStorageSync('selectAddId')
          that.setData({
            temporaryAddressData:temporaryAddressData
          })
          that.getAddressList()
         
        }
      }else{
        wx.showToast({
          title: '查询地址失败：'+res.data.msg,
          icon:'none'
        })
      }
    },true)
  },
  slectAddressData(e){  //选择已有收货地址
    var addrs=e.currentTarget.dataset.val
    this.setData({
      adrMy:addrs,
      modelPopupName:'',
    })
    wx.setStorageSync('selectAddId',addrs.id)
    wx.removeStorageSync('temporaryAddressData')
    this.getSelectAddr()
  },
  getAddressList(e){  //获取收货地址列表
    var that=this;
    var parms={ pageFlag:false }
    app.reqFun.requestForm('post',configUrl.addressList,parms,(res)=>{
      if(res.data.success==1){
        that.setData({
          addressListData:res.data.data.records
        })
        if(res.data.data.records.length>0){
          var adrMy=''
          var selectAddId=wx.getStorageSync('selectAddId')
          for(let adr of res.data.data.records){
            adr.isChecked=false
            if(selectAddId){
              if(adr.id==selectAddId){
                adr.isChecked=true
                adrMy=adr
              }
            }else if(adr.defaultStatus=="Y"){
              adr.isChecked=true
              adrMy=adr
            }
          }
          if(!adrMy){
            adrMy=res.data.data.records[0]
          }
          that.setData({adrMy:adrMy})  //默认收货地址
          that.setData({
            addressListData:res.data.data.records
          })
        }   
        that.getSelectAddr()    
      }
    })
  },
  getSelectAddr(){   //匹配地址获取数据
    var  personalAddr=this.data.adrMy;  //收货地址
    var  storageAddr=wx.getStorageSync('temporaryAddressData')
    var  locationAddr=wx.getStorageSync('addrCode')
    if(storageAddr){
      this.getDetails(storageAddr.streetName.code?storageAddr.streetName.code:storageAddr.region.code)
      this.setData({
        showAddress:getSpliceAddress(storageAddr.streetName.code?storageAddr.streetName.path:storageAddr.region.path)
      })
    }else if(personalAddr){
      this.getDetails(personalAddr.street?personalAddr.street:personalAddr.region)
      this.setData({
        showAddress:(personalAddr.provinceName+'-'+personalAddr.cityName+'-'+personalAddr.regionName+'-'+personalAddr.streetName)
      }) 
    }else{
      this.getDetails(locationAddr.townCode?locationAddr.townCode:locationAddr.districtCode)
      this.setData({
        showAddress:(locationAddr.province+'-'+locationAddr.city+'-'+locationAddr.district+'-'+locationAddr.townName)
      }) 
    }
  },
  onCloseModel2(){  //关闭选择地址弹窗
    this.setData({ modelPopupName:'',})
  },
  calculationPriceOrNumber(info){ //计算商品数及原价 、优惠价
    var number=0;
    var salesPrice=0
    for(let room of info.smsHouseBuyMealSpaceInfoDto){
      for(let spu of room.pmsHouseBuyProductDto){
        for(let sku of spu.skuStock){
          if(sku.isCheck){
            number=number+sku.amount
            salesPrice=salesPrice+sku.salesPrice
          }      
        }
      }
    }
    info.originalPrice=salesPrice.toFixed(2)
    info.discountPrice=(salesPrice-info.activityPrice).toFixed(2)
    info.allGoodsNum=number
    this.setData({
      infoData:info
    })
  },
  calculationBuyPrice(info){   //选择空间合计金额
    var totalAmount=0
    for(let room of info.smsHouseBuyMealSpaceInfoDto){
      if(room.checked){
        totalAmount=totalAmount+room.promotionPrice
      }
    }
    info.totalAmount=totalAmount
    this.setData({infoData:info})
  },
  goSettlement(){   //去结算
    var info = this.data.infoData
    console.log(info)
    var list=[]  //空间集合
    var listId=[]   //id集合
    for(let val of info.smsHouseBuyMealSpaceInfoDto){
      if(val.checked){
        list.push(val)
        listId.push(val.id)
      }
    }

    if(list.length>0){
      // 还需验证全屋购空间
      var params={listId}
      app.reqFun.requestJson('POST', verifySpaceValidation, listId, (res) =>{
        if(res.data){
          wx.setStorageSync('wholeHouseData', list)
            wx.setStorage({
              data: list,
              key: 'wholeHouseData',
              success: (res) => {
                wx.navigateTo({
                  url: '../../../confirmOrder/confirmOrder?type=wholeHouse',
                })
              },
            })
        }else{
          wx.showToast({
            title: '你选择的空间已下架，请刷新数据重试。',
            icon:'none',
            duration:3000
          })
        }
      })
      
     
    }else{

      wx.showToast({
        title: '请选择空间',
        icon: 'none',
        mask:true,
        duration: 2000
      })
    }
    
  },
  getReturnTime(time){   //处理活动倒计时--time=活动结束时间
    var that=this;
    that.setData({
      returnTime:{
        day:'00'+'天',
        hours:'00'+'小时',
        minute:'00'+'分',
        second:'00'+'秒'
      }
    })
    const getTime=parseInt((new Date(time.replace(/-/g,"/")).getTime() - new Date().getTime()))
    console.log(getTime)
    if(getTime<=0){
      that.setData({subBtnDis:true})
      that.getUpdateGoodInfo(that.data.skuId)
    }else{
      var nowSecond=getTime
    var setFun =  setInterval(() => {
        var d = parseInt(nowSecond /1000 /3600 /24)  //天   
        var h = parseInt(nowSecond / 1000 / 3600 % 24) //时
        var m = parseInt(nowSecond / 1000 / 60 % 60)   //分
        var s = parseInt(nowSecond / 1000  % 60) //秒
        // if(d>0){
        //   h=(d*24+h)
        // }
        that.setData({
          returnTime:{
            day:d+'天',
            hours:h>9?h+'小时':"0"+h+'小时',
            minute:m>9?m+'分':"0"+m+'分',
            second:s>9?s+'秒':"0"+s+'秒'
          }
        })
       
        nowSecond=nowSecond-1000
        if(nowSecond<=0){
          clearInterval(setFun)
          that.getUpdateGoodInfo(that.data.skuId)
        }
      }, 1000);
    }
  },
  goreBack(e) {
    wx.navigateBack({
      delta: 1,
    })
  },
  goHome() {
    wx.navigateTo({
      url: '/pages/newIndex/newIndex',
    })
  },
  goInfo(e){  //去详情
    var spu=e.currentTarget.dataset.val
    for(let val of spu.skuStock){
      if(val.isCheck){
        wx.navigateTo({
          url: '../../../../../packageShop/pages/goodsInfo/goodsInfo?id='+val.skuId,
        })
      }
    }

  },
  //登录-注册
  bindGetUserInfo: function (e) {
    app.getUserInfo()
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
  },
  //登录弹窗关闭回调
  onCloseShowGetUserInfo() {
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
  },
})

function getSpliceAddress(name){
  return name.replace("中国/", "").replace(/\//g, "-")
}